package org.mq.mymq.nameserver.handler;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.enums.NameServerEventCode;
import org.mq.mymq.common.event.EventBus;
import org.mq.mymq.common.event.model.Event;
import org.mq.mymq.nameserver.event.model.ReplicationMsgEvent;

/**
 * @ClassName MasterSlaveReplicationServerHandler
 * @Description 主从架构下从节点复制处理器
 * @Author jiarong_ye
 * @Date 2025/6/20 10:07
 * @Version 1.0
 */
@ChannelHandler.Sharable
public class SlaveReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {
    private EventBus eventBus;

    public SlaveReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
        this.eventBus.init();
    }

    /**
     * 1. 接收网络请求（netty）
     * 2. 事件发布器实现
     * 3. 事件处理器的视线
     * 4. 数据存储 基于map本地内存的方式存储
     *
     * @param channelHandlerContext
     * @param tcpMsg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        // 从节点发起链接，在master端通过密码验证建立链接
        // 链接建立后，master节点接收到数据，同步发送给slave节点
        Event event = null;
        if (NameServerEventCode.MASTER_REPLICATION_MSG.getCode() == code) {
            event = JSON.parseObject(body, ReplicationMsgEvent.class);
        }
        event.setChannelHandlerContext(channelHandlerContext);
        eventBus.publish(event);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
